﻿using System;
using System.Web;
using System.Text.RegularExpressions;

/// <summary>
/// 通用工具类
/// </summary>
public class Tools
{
	public Tools()
	{ }

    /// <summary> 
    /// 根据 Agent 判断是否是智能手机 
    /// </summary> 
    /// <returns></returns> 
    public static bool CheckAgent()
    {
        bool flag = false;
        string agent = HttpContext.Current.Request.UserAgent;
        string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };
        //排除Window 桌面系统 和 苹果桌面系统 
        if (!agent.Contains("Windows NT") && !agent.Contains("Macintosh"))
        {
            foreach (string item in keywords)
            {
                if (agent.Contains(item))
                {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

    /// <summary>
    /// 获取客户端IP
    /// </summary>
    /// <returns></returns>
    public static string GetClientIP()
    {
        string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.UserHostAddress;
        }
        return result;
    }

    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="argPass"></param>
    /// <returns></returns>
    public static string EncryptPasswordByMD5(string argPass)
    {
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(argPass, "MD5");
    }

    /// <summary>
    /// 过滤字符串中的非法字符串
    /// </summary>
    /// <param name="text"></param>
    /// <param name="maxLength"></param>
    /// <returns></returns>
    public static string ReplaceString(string text, int maxLength)
    {
        #region
        text = text.Trim();
        if (string.IsNullOrEmpty(text))
            return string.Empty;
        if (text.Length > maxLength)
            text = text.Substring(0, maxLength);
        text = Regex.Replace(text, "[\\s]{2,}", " "); //two or more spaces
        text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br>
        text = Regex.Replace(text, "(\\*)+", " "); //&nbsp;
        text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty);
        text = text.Replace("'", "''");
        return text;
        #endregion
    }
}
